<template>
    <div>
        <div class="buttonGroup">
            <el-button v-if="form.id && !disabled" @click="update">更 新</el-button>
            <el-button v-if="!form.id && !disabled" @click="save(false)">保 存</el-button>
            <el-button type="info" :icon="Close" @click="reback()">退 出</el-button>
        </div>
        <el-scrollbar :height="h">
            <el-form :model="form" label-position="right" ref="formRef" :rules="formRules"
                :class="{ borderNone: disabled }" :disabled="disabled">
                <ts-card header="基本信息">
                    <el-row :gutter="10">
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="销售合同" required>
                                <ts-select v-if="!disabled" v-model="form.omOrderId" :label="form.omOrderNo"
                                    fileName="WaitCovertOrderDtlReport" :template="omOrderTemplate"
                                    :mapping="omOrderMapping" @updateRow="updateOmOrder"></ts-select>
                                <span v-else>{{ form.omOrderNo }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="业务员">
                                <span>{{ form.salesName }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="订单批次号" required>
                                <el-input v-model="form.number">
                                    <template v-if="!disabled && form.custId" #append>
                                        <el-button :icon="Refresh" @click="getNumber" />
                                    </template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="报关操作" required>
                                <ts-select v-if="!disabled" v-model="form.customsOperatorId"
                                    :label="form.customsOperatorName" fileName="ChooseEmployeeReport"
                                    :template="customsOperatorTemplate"></ts-select>
                                <span v-else>{{ form.customsOperatorName }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <div style="
                  display: flex;
                  flex-direction: column;
                  margin-right: 5px;
                  margin-bottom: 18px;
                ">
                                <el-form-item label="客户" style="margin-bottom: 5px">
                                </el-form-item>
                                <el-input placeholder="客户姓名" v-model="form.custName" type="textarea"
                                    disabled></el-input>
                                <el-input style="margin-top: 5px" placeholder="客户地址" v-model="form.custAddress"
                                    type="textarea" disabled></el-input>
                                <el-input style="margin-top: 5px" v-model="form.custPhone" disabled></el-input>
                            </div>
                        </el-col>
                        <el-col :span="6">
                            <div style="
                  display: flex;
                  flex-direction: column;
                  margin-right: 5px;
                  margin-bottom: 18px;
                ">
                                <el-form-item style="margin-bottom: 5px" label="发货人">
                                </el-form-item>
                                <el-input placeholder="发货人姓名" v-model="form.shipperName" type="textarea"
                                    disabled></el-input>
                                <el-input style="margin-top: 5px" placeholder="发货人地址" v-model="form.shipperAddress"
                                    type="textarea" disabled></el-input>
                                <el-input style="margin-top: 5px" v-model="form.shipperPhone" disabled></el-input>
                            </div>
                        </el-col>
                        <el-col :span="6">
                            <div style="
                  display: flex;
                  flex-direction: column;
                  margin-right: 5px;
                  margin-bottom: 18px;
                ">
                                <el-form-item style="margin-bottom: 5px" label="收货人">
                                </el-form-item>
                                <el-input placeholder="收货人姓名" v-model="form.consigneeName" type="textarea"
                                    disabled></el-input>
                                <el-input style="margin-top: 5px" placeholder="收货人地址" v-model="form.consigneeAddress"
                                    type="textarea" disabled></el-input>
                                <el-input style="margin-top: 5px" v-model="form.consigneePhone" disabled></el-input>
                            </div>
                        </el-col>
                        <el-col :span="6">
                            <div style="
                  display: flex;
                  flex-direction: column;
                  margin-right: 5px;
                  margin-bottom: 18px;
                ">
                                <el-form-item label="通知人" style="margin-bottom: 5px">
                                </el-form-item>
                                <el-input placeholder="通知人姓名" v-model="form.notifierName" type="textarea"
                                    disabled></el-input>
                                <el-input style="margin-top: 5px" placeholder="通知人地址" v-model="form.notifierAddress"
                                    type="textarea" disabled></el-input>
                                <el-input style="margin-top: 5px" v-model="form.notifierPhone" disabled></el-input>
                            </div>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="报关单位名称">
                                <el-input style="margin-top: 5px" v-model="form.sellerName" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="报关单位代码">
                                <el-input v-model="form.customsCompanyCode" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="统一社会信用代码">
                                <el-input style="margin-top: 5px" v-model="form.unifiedSocialCode" disabled></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="10">
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="开户行" required>
                                <sc-table-select v-if="!disabled" v-model="bankRow" :props="bankTemplate"
                                    fileName="CompanyAccountReport" :initForm="initSelectForm"
                                    @change="bankChange"></sc-table-select>
                                <span v-else>{{ form.customsOperatorName }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                            <el-form-item label="代理行" required>
                                <span>{{ form.correspondentBankName }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </ts-card>
                <ts-card header="订舱信息">
                    <el-row :gutter="10">
                        <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                            <el-form-item label="订舱日期" required>
                                <el-date-picker v-model="form.bookingDate" value-format="YYYY-MM-DD" />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                            <el-form-item label="实际发货时间" required>
                                <el-date-picker v-model="form.deliveryTime" value-format="YYYY-MM-DD" />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="货代" required>
                                <ts-select v-if="!disabled" v-model="form.supplierId" :label="form.supplierName"
                                    fileName="SupplierReport" :template="customsOperatorTemplate"></ts-select>
                                <span v-else>{{ form.supplierName }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="船名航次" required>
                                <el-input v-model="form.voyage"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="提单号" required>
                                <el-input v-model="form.billOfLadingNo"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="柜型及数量" required>
                                <el-input v-model="form.sizeAndQty"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="运费(外币)" required>
                                <el-input v-model="form.freight" type="number" @change="freightChange"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="港杂费(CNY)" required>
                                <el-input v-model="form.portCharges" type="number"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="保险费(CNY)" required>
                                <el-input v-model="form.premiums" type="number"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </ts-card>
                <ts-card header="报关信息">
                    <el-row :gutter="10">
                        <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                            <el-form-item label="报关日期" required>
                                <el-date-picker v-model="form.customsDeclarationDate" value-format="YYYY-MM-DD" />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="贸易国">
                                <el-select v-model="form.tradingState" clearable filterable placeholder="请选择：">
                                    <el-option v-for="item in configData.countryList" :key="item.value"
                                        :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="运抵国">
                                <el-select v-model="form.arrivalCountry" clearable filterable placeholder="请选择：">
                                    <el-option v-for="item in configData.countryList" :key="item.value"
                                        :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="指运港" required>
                                <el-input v-model="form.destinationPort"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                            <el-form-item label="离港口岸" required>
                                <el-input v-model="form.portOfDeparture"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </ts-card>
                <ts-card header="订舱产品">
                    <sc-form-table v-model="dataList" dragSort onlyDelete @delete="rowDelete" placeholder="暂无数据">
                        <template #tableContent>
                            <el-table-column label="发票号" width="200">
                                <template #default="scope">
                                    <el-input v-model="scope.row.invoiceNumber"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="订舱英文名" prop="bookingSpaceEnName" width="200">
                            </el-table-column>
                            <el-table-column label="报关英文名" width="200">
                                <template #default="scope">
                                    <el-input v-model="scope.row.customsDeclarationEnName" type="textarea"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="报关中文名" prop="customsDeclarationName" width="150"></el-table-column>
                            <el-table-column label="HS CODE" prop="hscode" width="100"></el-table-column>
                            <el-table-column label="危险品信息" prop="dangerousKind" width="100"></el-table-column>
                            <el-table-column label="含进仓费" prop="includeWarehouseFees" width="100"></el-table-column>
                            <el-table-column label="出货数" width="120">
                                <template #default="scope">
                                    <el-input-number style="width: 95%;padding: 0px" v-model="scope.row.qty"
                                        @change="handlePrice(scope.row)" :max="scope.row.waitingSoQty"
                                        controls-position="right" />
                                </template>
                            </el-table-column>
                            <el-table-column label="件数" prop="pieces" width="120"></el-table-column>
                            <el-table-column label="单位体积" prop="volume" width="120"></el-table-column>
                            <el-table-column label="体积" prop="totalVolume" width="120"></el-table-column>
                            <el-table-column label="单位毛重" prop="grossWeight" width="120">
                            </el-table-column>
                            <el-table-column label="毛重" prop="totalGrossWeight" width="120">
                            </el-table-column>
                            <el-table-column label="单位净重" prop="netWeight" width="120">
                            </el-table-column>
                            <el-table-column label="净重" prop="totalNetWeight" width="120">
                            </el-table-column>
                            <el-table-column label="FOB总价" prop="totalAmount" width="120">
                            </el-table-column>
                            <el-table-column label="报关运费" prop="customsDeclarationFreight" width="120">
                            </el-table-column>
                            <el-table-column label="报关金额" prop="customsDeclarationAmount" width="120">
                            </el-table-column>
                            <el-table-column label="保费" width="120">
                                <template #default="scope">
                                    <el-input-number style="width: 95%;padding: 0px" v-model="scope.row.premiums"
                                        controls-position="right" />
                                </template>
                            </el-table-column>
                            <el-table-column label="包装种类" width="180">
                                <template #default="scope">
                                    <el-select v-model="scope.row.packagingType" clearable filterable
                                        placeholder="请选择：">
                                        <el-option v-for="item in configData.packagingTypeList" :key="item.value"
                                            :label="item.label" :value="item.value">
                                        </el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="货源地" width="200">
                                <template #default="scope">
                                    <el-input v-model="scope.row.goodsOrigPlace"></el-input>
                                </template>
                            </el-table-column>
                        </template>
                        <template #append>
                            <div style="display: flex; background-color: #fff1d4">
                                <div style="display: flex; padding: 8px 0">
                                    <div class="sum_footer_unit" style="width: 1530px">合计</div>
                                    <div class="sum_footer_unit" style="width: 240px">
                                        {{ tool.groupSeparator(form.totalVolume) }}
                                    </div>
                                    <div class="sum_footer_unit" style="width: 240px">
                                        {{ tool.groupSeparator(form.totalGrossWeight) }}
                                    </div>
                                    <div class="sum_footer_unit" style="width: 120px">
                                        {{ tool.groupSeparator(form.totalNetWeight) }}
                                    </div>
                                    <div class="sum_footer_unit" style="width: 240px">
                                        {{ tool.groupSeparator(form.totalAmount) }}
                                    </div>
                                    <div class="sum_footer_unit">
                                        {{ tool.groupSeparator(form.customsDeclarationAmount) }}
                                    </div>
                                </div>
                            </div>
                        </template>
                    </sc-form-table>
                </ts-card>
            </el-form>
        </el-scrollbar>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted, computed, watch } from "vue";
import { ElNotification } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { Refresh, Close } from "@element-plus/icons-vue";
import Api from "@/api/model/om";
import tsSelect from "@/components/scSelect/index.vue";
import { deepClone } from "@/utils/arr";
import useTabs from "@/utils/useTabs";
import tool from "@/utils/tool";
const emit = defineEmits(["updatetable"]);
const route = useRoute();
const router = useRouter();
const props = defineProps({
    paramsData: {
        type: Object,
        defalut: {},
    },
});
const h = computed(() => {
    let height;
    var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
    if (!iOS) {
        height = window.innerHeight;
    } else {
        height = screen.height;
    }
    return height - 150;
});
const omOrderTemplate = {
    label: "omOrderNo",
    value: "omOrderId",
};
const customsOperatorTemplate = {
    label: "name",
    value: "id",
};
const bankTemplate = {
    label: 'bankName',
    value: 'bankName'
}
const omOrderMapping = [
    { value: "number", label: "omOrderNo" },
    { value: "id", label: "omOrderId" },
];
const initSelectForm = computed(() => {
    return {
        masterId: form.value.customsCompanyId,
    };
});
const bankRow = ref({
    bankName: ''
})
// 添加用户数据的对象
const form = ref({});
const disabled = ref(false);
const configData = ref([]);
const formRef = ref();
const formRules = reactive({});
const dataList = ref([]);
const deleteDataList = ref([]);
const optType = ref();
watch(dataList, (newValue, oldValue) => {
    form.value.totalAmount = tool.formatRoundNum(dataList.value.reduce(
        (sum, e) => sum + Number(e.totalAmount || 0),
        0
    ), 2);
    form.value.totalGrossWeight = tool.formatRoundNum(dataList.value.reduce(
        (sum, e) => sum + Number(e.totalGrossWeight || 0),
        0
    ), 2);
    form.value.totalNetWeight = tool.formatRoundNum(dataList.value.reduce(
        (sum, e) => sum + Number(e.totalNetWeight || 0),
        0
    ), 2);
    form.value.totalVolume = tool.formatRoundNum(dataList.value.reduce(
        (sum, e) => sum + Number(e.totalVolume || 0),
        0
    ), 3);
    form.value.customsDeclarationAmount = tool.formatRoundNum(dataList.value.reduce(
        (sum, e) => sum + Number(e.customsDeclarationAmount || 0),
        0
    ), 2);
}, { deep: true })
onMounted(() => {
    optType.value = route.query.optType;
    console.log(route.query)
    if (route.query.id || route.query.rowIds) {
        getInit();
    }
});

const getInit = async (val) => {
    if (optType.value === "detail") {
        disabled.value = true;
    }
    let res;
    let param = val ? val : route.query;
    if (optType.value === "add") {
        res = await Api.shippingOrder.add.post(param);
    } else {
        res = await Api.shippingOrder.detail.post(param);
    }
    if (res.code == "200") {
        configData.value = res.configData;
        form.value = deepClone(res.data);
        dataList.value = res.dataList;
        bankRow.value.bankName = form.value.bankName
        dataList.value.forEach(ele => {
            handlePrice(ele)
        })
    }
};
const updateOmOrder = async (val) => {
    getInit({ id: val.omOrderId })
};
const getNumber = async () => {
    let res = await Api.shippingOrder.generatePoOrderNo.post({
        id: form.value.custId,
    });

    if (res.code === "200") {
        form.value.number = res.number;
    }
};
const bankChange = (val) => {
    form.value.bankName = val.bankName
    form.value.correspondentBankName = val.correspondentBankName
};
const freightChange = () => {
    dataList.value.forEach((ele, index) => {
        if (ele.qty) {
            if (index !== (dataList.value.length - 1)) {
                ele.customsDeclarationFreight = tool.formatRoundNum(form.value.freight / form.value.totalGrossWeight * ele.totalGrossWeight, 2)
            }
        }
    })
    let arr = deepClone(dataList.value)
    arr.pop()
    let totalfreight = tool.formatRoundNum(arr.reduce(
        (sum, e) => sum + Number(e.customsDeclarationFreight || 0),
        0
    ), 2);
    if (totalfreight > 0 || dataList.value.length === 1) {
        dataList.value[dataList.value.length - 1].customsDeclarationFreight = tool.formatRoundNum(form.value.freight - totalfreight, 2)
        // dataList.value[dataList.value.length - 1].customsDeclarationAmount = tool.formatRoundNum(dataList.value[dataList.value.length - 1].totalAmount + dataList.value[dataList.value.length - 1].customsDeclarationFreight, 2)
        // dataList.value[dataList.value.length - 1].premiums = tool.formatRoundNum(dataList.value[dataList.value.length - 1].customsDeclarationAmount * 1.1 * 0.001, 2)
    }

}
const rowDelete = (val) => {
    deleteDataList.value.push(val);
};
const handlePrice = (row) => {
    row.pieces = tool.formatRoundNum(row.qty / Number(row.mtlSpec), 2);
    row.totalAmount = tool.formatRoundNum(row.omPrice * row.qty, 2);
    row.totalGrossWeight = tool.formatRoundNum(row.grossWeight * row.pieces, 2);
    row.totalVolume = tool.formatRoundNum(row.volume * row.pieces, 3);
    row.totalNetWeight = tool.formatRoundNum(row.netWeight * row.pieces, 2);
    row.customsDeclarationAmount = tool.formatRoundNum(row.cifPrice * row.qty, 2)
    row.premiums = tool.formatRoundNum(row.customsDeclarationAmount * 1.1 * 0.001, 2)

    freightChange()
};
const save = async (val) => {
    let param = {
        bean: form.value,
        dataList: dataList.value.filter((ele) => {
            return ele.mtlId;
        }),
    };
    console.log(param);
    let res = await Api.shippingOrder.save.post(param);
    console.log(res);
    if (res.code == "200") {
        optType.value === "save";
        ElNotification.success({
            title: "",
            message: "添加成功！",
            duration: 2000,
        });
        reback()
    }
};
const update = async () => {
    let param = {
        bean: form.value,
        dataList: dataList.value.concat(deleteDataList.value).filter((ele) => {
            return ele.mtlId;
        }),
    };
    let res = await Api.shippingOrder.update.post(param);
    if (res.code == "200") {
        ElNotification.success({
            title: "",
            message: "更新成功！",
            duration: 2000,
        });
        reback()
        // getInit({ id: res.id });
    }
};
const reback = () => {
    useTabs.close();
    router.push({
        path: "/shippingOrderList/ShippingOrderReport",
    });
    route.isRefrensh = true;
};
</script>
<style lang="less" scoped>
.buttonGroup {
    align-items: center;
    box-sizing: border-box;
    display: flex;
    height: 48px;
    justify-content: flex-end;
    margin-bottom: 12px;
    padding: 10px 16px;
    font-size: 12px;
    list-style-type: none;
    text-align: left;
    background-color: #ffffff;
}

.borderNone {
    :deep(.el-input__wrapper) {
        box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
        cursor: default;
        background-color: transparent; //背景颜色透明
        border-bottom: 1px solid #999;
        border-radius: 0;

        .el-input__inner {
            cursor: default !important;
        }
    }

    :deep(.el-textarea__inner) {
        box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
        cursor: default;
        background-color: transparent; //背景颜色透明
        border-bottom: 1px solid #999;
        border-radius: 0;
    }
}

.sum_footer_unit {
    height: 23px;
    line-height: 23px;
    padding: 0 12px;
    font-size: 14px;
    font-weight: 600;
    text-align: left;
}
</style>